<template>
    <div class="body">
        <van-config-provider :theme-vars="themeVars">
            <van-nav-bar style="background-color: rgba(0, 0, 0, 0);" title="发布" left-text="返回" left-arrow
                @click-left="onClickLeft">
                <template #right>
                    <van-icon @click="publish()" name="success" />
                </template>
            </van-nav-bar>
            <div class="content">
                <!-- 标题输入框 -->
                <van-field class="input" v-model="title" type="textarea" rows="1" placeholder="一句话表达你的想法" autosize />
                <!-- 内容输入框 -->
                <van-field class="input" v-model="content" type="textarea" rows="6" placeholder="来吧，畅所欲言吧..."
                    maxlength="120" show-word-limit autosize />
            </div>


            <van-uploader :before-read="beforeRead" :after-read="onAfterRead" class="tu" v-model="fileList" multiple
                upload-icon="plus">
            </van-uploader>
        </van-config-provider>


    </div>
</template>

<script setup>
import axios from 'axios';
import { reactive, ref } from 'vue';
import { useRouter } from 'vue-router';
// 主题色变量
const themeVars = reactive({
    navBarIconColor: '#C94B29',
    navBarTextColor: '#C94B29',
    // placeholder 颜色
    fieldPlaceholderTextColor: '#969799',
    // 上传图标色
    uploaderIconColor: '#C94B29',
});

const title = ref('');
const content = ref('');
const fileList = ref([]);
let router = useRouter();
const onClickLeft = () => history.back();


// 发布
async function publish() {
    const fls = fileList.value.map(item => item.url)
    const { data: { status } } = await axios.post("http://localhost:3000/addPost", {
        title: title.value,
        content: content.value,
        userId: localStorage.getItem("userId") || "6720a1691e035a31d203787d",
        img: fls,
        tribeId: localStorage.getItem("tribe") || "6720a0288878a9b1e096e206",
    });
    if (status == 200) {
        showNotify({ type: 'success', message: '发布成功' });
        //延迟跳转
        setTimeout(() => {
            router.push('/tribe')
        }, 1000);
    }
}
const beforeRead = (file) => {
    // 返回 true 允许上传，返回 false 阻止上传
    return true;
};

const onAfterRead = (file) => {
    const formData = new FormData();
    formData.append('file', file.file);

    axios.post('http://localhost:3000/uploads', formData, {
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    }).then(response => {
        console.log('文件上传成功:', response.data);
        // 将上传成功的文件信息加入 fileList
        fileList.value.push({
            url: response.data.url,
            name: file.file.name
        });
        const index = fileList.value.findIndex(item => item.file?.name === file.file.name);
        console.log('index:', index);
        fileList.value.splice(index, 1);


        console.log('fileList:', fileList.value);
    }).catch(error => {
        console.error('文件上传失败:', error);
    });
};

</script>

<style lang="less" scoped>
.body {
    background-color: #FEF9EF;
    min-height: 100vh;
}

.input {
    width: 94%;
    background-color: #F5EBDE;
    margin: 10px auto;
    border-radius: 5px;
}

.tu {
    margin: 10px;
    border-radius: 5px;
}
</style>